package com.hs.egova.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author husheng
 * @version v1.0
 * @date 2021/7/20 14:07
 * @email husheng@egova.com.cn
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {
    /**
     * 定义切面
     */
    @Pointcut("execution(public * com.hs.egova.controller..*.*(..))")
    public void pointcut() {}

    /**
     *
     * @param joinPoint
     */
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        log.info("进入doBefore");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //打印日志
        log.info("访问开始： {}", System.currentTimeMillis());
        log.info("url: {}", request.getRequestURL());
        log.info("HTTP_METHOD {}", request.getMethod());
        log.info("Args{}", Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "pointcut()")
    public void doAfter(Object ret) throws Throwable {
        //访问结束
        log.info("访问结束：{}", System.currentTimeMillis());
    }
}
